package com.openroom.ui.component;

import java.net.URL;
import java.util.List;

import org.apache.pivot.beans.BXMLSerializer;
import org.apache.pivot.collections.Map;
import org.apache.pivot.util.Resources;
import org.apache.pivot.wtk.BoxPane;
import org.apache.pivot.wtk.Container;

import com.openroom.event.ApplicationEvent;
import com.openroom.event.EventHandler;
import com.openroom.event.EventManager;
import com.openroom.event.EventType;
import com.openroom.model.ModelLocator;
import com.openroom.model.Photograph;
import com.openroom.model.ModelLocator.ModeFlag.ImageViewMode;
import com.openroom.ui.MainWindow;
import com.openroom.ui.UIComponent;

public class TnailStrip extends BoxPane implements UIComponent {

    private static int originalWidth = 0;
    
    @Override
    public void initialize(Map<String, Object> namespace, URL arg1,
            Resources arg2, MainWindow window) {

        EventManager.getInstance().listenToEventType(
                EventType.ALL_SHOWING_IMAGE_CHANGED, new EventHandler() {
                    @Override
                    public void handle(ApplicationEvent event) {
                        List<Photograph> allShowingImage = ModelLocator
                                .getInstance().getAllShowingImage();
                        removeAll();
                        for (Photograph photo : allShowingImage) {
                            try {
                                add(getImageView(photo));
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });

        EventManager.getInstance().listenToEventType(new EventHandler() {

            @Override
            public void handle(ApplicationEvent event) {
                if (!ModelLocator.getInstance().getCurrentImageMode()
                        .equals(ImageViewMode.THUMBNAIL)) {
                    getParent().setVisible(true);
                }
                else
                {
                    getParent().setVisible(false);
                }
            }
        }, EventType.VIEW_MODE_CHANGED);
    }

    @Override
    protected void layout() {
        super.layout();
        originalWidth = getHeight();
    }
    
    private Container getImageView(final Photograph image) throws Exception {
        BXMLSerializer bxmlSerializer = new BXMLSerializer();
        final ThumbnailView component = (ThumbnailView) bxmlSerializer
                .readObject(MainWindow.class, "tnailSmall.xml");
        component.initialize(bxmlSerializer.getNamespace(), null, null);
        component.setImage(image);
        component.setWidth(72);
        component.setHeight(90);
        return component;
    }
}
